<?php
// 教师管理综合页：列出，删除，导入，无编辑功能
$pageTitle = "教师管理";
include 'header.php';

// 获取搜索关键词
$search_name = isset($_GET['name']) ? trim($_GET['name']) : '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file'];

    if ($file['error'] === UPLOAD_ERR_OK) {
        $tmp_name = $file['tmp_name'];
        $l1 = true;
        // 打开CSV文件以供读取
        if (($handle = fopen($tmp_name, 'r')) !== false) {
            try {
                // 开启 pdo 事处
                $pdo->beginTransaction();
                // 插入数据库记录
                $stmt = $pdo->prepare(
                    'INSERT INTO teachers (
                                name,
                                subject,
                                work_time,
                                phone,
                                sex,
                                birthday,
                                school,
                                here_work_time,
                                grade,
                                major,
                                educational,
                                qualifications,
                                qualifications_time,
                                master_level
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
                );
                // 逐行读取CSV文件
                while (($data = fgetcsv($handle, 1000, ',')) !== false) {
                    if ($l1) {
                        $l1 = false;
                        if (strpos($data[0], "\xEF\xBB\xBF") === 0) {
                            $data[0] = substr($data[0], 3);
                        }
                        if ($data[0] == '姓名') continue;
                        if ($data[1] == '性别') continue;
                    }

                    if (count($data) >= 13) {
                        //姓名,性别,出生日期,参加工作时间,入职山阳区工作时间,任教学科,年级,专业,学历,职称,职称证取得时间,名师骨干层次,联系电话
                        $name = $data[0];
                        $sex = $data[1];
                        $birthday = $data[2];
                        $work_time = $data[3];
                        $here_work_time = $data[4];
                        $subject = $data[5];
                        $grade = $data[6];
                        $major = $data[7];
                        $educational = $data[8];
                        $qualifications = $data[9];
                        $qualifications_time = $data[10];
                        $master_level = $data[11];
                        $phone = $data[12];
                        $school = $_SESSION['school'];


                        // 插入数据到数据库
                        $stmt->execute([
                            $name,
                            $subject,
                            $work_time,
                            $phone,
                            $sex,
                            $birthday,
                            $school,
                            $here_work_time,
                            $grade,
                            $major,
                            $educational,
                            $qualifications,
                            $qualifications_time,
                            $master_level
                        ]);
                    }
                }
                $pdo->commit();

                echo "教师信息已成功导入！";
            } catch (PDOException $e) {
                $pdo->rollBack();
                die('数据库操作失败: ' . $e->getMessage());
            }
            // 关闭文件句柄
            fclose($handle);
        } else {
            echo "无法打开CSV文件。";
        }
    } else {
        echo "请输入有效的CSV数据。";
    }
}
?>
<style>
    table {
        border-collapse: collapse;
        margin-top: 20px;
        width: 100%;
    }

    table,
    th,
    td {
        border: 1px solid #999;
    }

    th,
    td {
        padding: 8px;
        text-align: left;
    }
</style>
<div class="row">
    <div class="card login-card">
        <div class="card-body">
            <h2 class="card-title text-center mb-4">导入教师信息</h2>
            <form action="teachers.php" method="post" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="csv_file">CSV数据格式教师导入信息（姓名,性别,出生日期,参加工作时间,入职山阳区工作时间,任教学科,年级,专业,学历,职称,职称取得时间,名师骨干层次,联系电话）：</label>
                    <input type="file" name="csv_file" accept=".csv">
                </div>
                <input type="submit" name="import_btn" value="导入" />
            </form>
        </div>
    </div>
    <div class="card login-card">
        <div class="card-body">
            <h2 class="card-title text-center mb-4">教师列表</h2>

            <!-- 搜索表单 -->
            <div class="mb-3">
                <form method="get" action="teachers.php" class="form-inline">
                    <div class="input-group">
                        <input type="text" name="name" class="form-control" placeholder="按姓名搜索" value="<?= htmlspecialchars($search_name) ?>">
                        <button class="btn btn-outline-secondary" type="submit">搜索</button>
                        <?php if (!empty($search_name)): ?>
                            <a href="teachers.php" class="btn btn-outline-secondary">清除</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>

            <table class="text-small">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>出生年月</th>
                        <th>参加工作时间</th>
                        <th>入职山阳区工作时间</th>
                        <th>任教学科及年级</th>
                        <th>学历及专业</th>
                        <th>职称及取得时间</th>
                        <th>名师骨干层次</th>
                        <th>单位</th>
                        <th>电话</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // 从数据库中获取教师信息并显示在表格中
                    $sql = "SELECT * FROM teachers";
                    if ($_SESSION['username'] != 'admin') {
                        $sql .= " WHERE school = '{$_SESSION['school']}'";
                        if (!empty($search_name)) {        // 添加搜索条件
                            $sql .= " AND name LIKE '%$search_name%'";
                        }
                    } else if (!empty($search_name)) {        // 添加搜索条件
                        $sql .= " WHERE name LIKE '%$search_name%'";
                    }

                    $sql .= " ORDER BY name";

                    $idx = 1;
                    $stmt = $pdo->query($sql);
                    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
                        <tr>
                            <td><?= $idx ?></td>
                            <td><?= $row['name'] ?></td>
                            <td><?= $row['sex'] ?></td>
                            <td><?= $row['birthday'] ?></td>
                            <td><?= $row['work_time'] ?></td>
                            <td><?= $row['here_work_time'] ?></td>
                            <td><?= $row['grade'] . '<br>' . $row['subject'] ?></td>
                            <td><?= $row['educational'] . '<br>' . $row['major'] ?></td>
                            <td><?= $row['qualifications'] . '<br>' . $row['qualifications_time'] ?></td>
                            <td><?= $row['master_level'] ?></td>
                            <td><?= $row['school'] ?></td>
                            <td><?= $row['phone'] ?></td>
                            <td>
                                <a href="teacher_edit.php?id=<?= $row['id'] ?>" class="btn btn-outline-secondary">编辑</a>
                                <a href="teacher_delete.php?id=<?= $row['id'] ?>" class="btn btn-outline-secondary">删除</a>
                                <a href="teacher_trainings.php?id=<?= $row['id'] ?>" class="btn btn-outline-secondary">培训列表</a>
                            </td>
                        </tr>
                    <?php $idx++;
                    } ?>
                </tbody>
            </table>
            <div><a href="teacher_delete_all.php" class="btn btn-outline-secondary">清空数据</a></div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>